import {
  AGConnectAuthCredential,
  AGConnectUser,
  EmailAuthProvider,
  VerifyCodeAction,
  VerifyCodeResult,
} from '@hw-agconnect/auth-ohos';
import '@hw-agconnect/auth-ohos';
import { PhoneAuthProvider, VerifyCodeSettingBuilder } from '@hw-agconnect/auth-ohos';
import { AGCApi } from '@hw-agconnect/api-ohos';
import { AppStorageUtils } from '../common/AppStorageUtils'
import { Log } from '../common/Log';
import { getAGConnect } from './AgcConfig';
import Prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
import { getContext } from '@hw-agconnect/hmcore';
import { Constants } from '../common/Constants';
import { userIcon } from '../models/userIcon';
import DBUtils from './DBUtils';


const TAG = "[AGCAuth]";

export class AGCAuth {
  agc: AGCApi;

  constructor(context) {
    this.agc = getAGConnect(context);
  }

  public getCurrentUser(): Promise<AGConnectUser> {
    return this.agc.auth().getCurrentUser();
  }

  /*获取用户头像*/
  public static async getIcon(uid: string): Promise<string> {
    /**
     * 返回用户头像的访问路径
     */
    try{
      const userIcons: userIcon[] = await DBUtils.userIconQueryByUid([uid])  // 根据用户ID查询该用户的头像图片路径
      Log.info(TAG,  JSON.stringify(userIcons))
      if (userIcons && userIcons.length > 0){
        return userIcons[0].icon
      }else{
        // 默认的用户头像图片,随机取一个
        const randomIndex = Math.floor(Math.random() * Constants.USER_HEAD_IMG_URLS.length)
        return Constants.USER_HEAD_IMG_URLS[randomIndex]
        // return 'https://agc-storage-drcn.platform.dbankcloud.cn/v0/subject-rb5ur/user_icon%2Fic_public_avatar7.png?token=c533f013-ccee-475e-9ce6-73ed39645ea4'
      }
    }catch (err){
      Log.error(TAG, '登陆失败:' + JSON.stringify(err))
      throw err
    }
  }

  //发送手机验证码
  public requestPhoneVerifyCode(ctrCode: string = '+86', phone: string) {
    //promptAction.showToast({message:'发送验证码成功'})
    let verifyCodeSettings = new VerifyCodeSettingBuilder()
      .setAction(VerifyCodeAction.REGISTER_LOGIN)
      .setLang('zh_CN')
      .setSendInterval(60)
      .build();
    this.agc.auth().requestPhoneVerifyCode(
      ctrCode,
      phone,
      verifyCodeSettings).then((ret) => {
      promptAction.showToast({ message: '发送验证码成功' })
      Log.info(TAG, JSON.stringify({ "Verify Code Result: ": ret }));
    }).catch((error) => {
      Log.error(TAG, "Error: " + JSON.stringify(error));
    });
  }
  // 2、发送邮箱验证码

  public requestEmailVerifyCode(email: string) {
    let verifyCodeSettings = new VerifyCodeSettingBuilder()
      .setAction(VerifyCodeAction.REGISTER_LOGIN)
      .setLang('zh_CN')
      .setSendInterval(120)
      .build();
    this.agc.auth().requestEmailVerifyCode(
      email,
      verifyCodeSettings).then((ret) => {
      promptAction.showToast({ message: '发送验证码成功' })
      Log.info(TAG, JSON.stringify({ "Verify Code Result: ": ret }));
    }).catch((error) => {
      Log.error(TAG, "Error: " + JSON.stringify(error));
    });
  }
  //登录
  public async login(isPhone: boolean, email: string, countryCode: string, phoneNumber: string, verifyCode: string): Promise<AgUser> {
    if (isPhone) {
      //手机验证码登录
      return new Promise((resolve, reject) => {
        const credential = PhoneAuthProvider.credentialWithVerifyCode(countryCode, phoneNumber, verifyCode);
        this.agc.auth().signIn(credential).then(async (ret) => {
          //Log.info(TAG, "User has signed in..");
          // @ts-ignore
          let user = ret.getUser();
          let userExtra = await ret.getUser().getUserExtra();

          let loginRes = new AgUser(
            user.getUid(),
            user.getPhotoUrl(),
            user.getPhone(),
            user.getEmail(),
            user.getDisplayName(),
            userExtra.getCreateTime(),
            userExtra.getLastSignInTime())

          resolve(loginRes);
          Log.info(TAG, "User has signed in with userID：" + loginRes.uid);
        }).catch((error) => {
          Log.error(TAG, "Error: ", error);
          reject(error);
        });
      });
    } else {
      //邮箱登录
      return new Promise((resolve, reject) => {
        // 得到一个认证凭据
        const result: AGConnectAuthCredential = EmailAuthProvider.credentialWithVerifyCode(email, verifyCode)
        // 用户登录
        this.agc.auth().signIn(result).then(async (ret) => {
          let user = ret.getUser();
          let userExtra = await ret.getUser().getUserExtra();
          let loginRes = new AgUser(
            user.getUid(),
            user.getPhotoUrl(),
            user.getPhone(),
            user.getEmail(),
            user.getDisplayName(),
            userExtra.getCreateTime(),
            userExtra.getLastSignInTime())
          resolve(loginRes);
          Log.info(TAG, "User has signed in with userID：" + loginRes.uid);
        })
          .catch((error) => {
            Log.error(TAG, "Error: ", error);
            reject(error);
          })
      });
    }

  }
//用户登出
  public async logout(): Promise<boolean> {
    return new Promise<boolean>((resolve, reject) => {
      this.agc.auth().signOut().then(() => {
        resolve(true);
        Log.info(TAG, "logout ok!", resolve);
      }).catch((error) => {
        Log.error(TAG, "error1", error);
        reject(error);
      });
    });
  }

  public async deleteUser(): Promise<boolean> {
    return new Promise((resolve, reject) => {
      this.agc.auth().deleteUser().then(() => {
        resolve(true);
      }).catch((error) => {
        Log.error(TAG, "error", error);
        reject(error);
      });
    });
  }
}

export class AgUser {
  uid: String;
  photoUrl: String;
  phone: String;
  email: String;
  displayName: String;
  registerDate: String;
  lastLogin: String;

  constructor(uid: String = "", photoUrl: String = "", phone: String = "", email: String = "", displayName: String = "", registerDate: String = "", lastLogin: String = "") {
    this.uid = uid;
    this.photoUrl = photoUrl;
    this.phone = phone;
    this.email = email;
    this.displayName = displayName;
    this.registerDate = registerDate;
    this.lastLogin = lastLogin;
  }

  getUid(): String {
    return this.uid;
  }

  getPhone(): String {
    return this.phone;
  }

  getEmail(): String {
    return this.email;
  }

  getDisplayName(): String {
    return this.displayName;
  }

  getPhotoUrl(): String {
    return this.photoUrl;
  }

  getRegisterDate(): String {
    return this.registerDate;
  }

  getLastLogin(): String {
    return this.lastLogin;
  }
}

function loginUser<T>(loginUser: any, arg1: any) {
  throw new Error('Function not implemented.');
}
